import { useStorage } from '@vueuse/core';
import { defineStore } from 'pinia';
import { loginApi, logoutApi } from '@/api/auth';
import { LoginData, UserInfo } from '@/api/auth/types';
import { store } from '@/store';

export const useUserStore = defineStore('user', () => {
  const user: UserInfo = {
    username: '',
    roles: [],
    perms: [],
  };

  const token = useStorage('accessToken', '');

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          const { accessToken } = response.data;
          token.value = accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          token.value = '';
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error: any) => {
          reject(error);
        });
    });
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      token.value = '';
      resolve();
    });
  }

  return {
    token,
    user,
    login,
    logout,
    resetToken,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
